package geotags

/*
Copyright 2021-2025 The k8gb Contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated by GoLic, for more details see: https://github.com/AbsaOSS/golic
*/

import (
	"context"
	"fmt"
	"net"
	"testing"
	"time"

	"github.com/k8gb-io/k8gb/controllers/resolver"
	"github.com/k8gb-io/k8gb/controllers/utils"
	"github.com/stretchr/testify/assert"
)

func TestParentDNS_Local_GetExternalClusterNSNamesByHostname(t *testing.T) {
	const server = "127.0.0.1"
	const port = 1053
	if !isDNSRunning(server, port) {
		t.Skipf("skipping test, edge DNS %s:%d is not running.", server, port)
	}

	tests := []struct {
		name          string
		config        *resolver.Config
		expectedError bool
		host          string
		result        map[string]string
	}{
		{
			name: "hit cloud.example.com",
			config: &resolver.Config{
				ClusterGeoTag: "us",
				DelegationZones: []*resolver.DelegationZoneInfo{
					{
						ParentZone:       "example.com",
						LoadBalancedZone: "cloud.example.com",
					},
				},
				ParentZoneDNSServers: []utils.DNSServer{{
					Host: server,
					Port: port,
				}},
			},
			expectedError: false,
			host:          "app.cloud.example.com",
			result: map[string]string{
				"eu": "gslb-ns-eu-cloud.example.com",
			},
		},
		{
			name: "hit cloud.example.com with three clusters",
			config: &resolver.Config{
				ClusterGeoTag: "za",
				DelegationZones: []*resolver.DelegationZoneInfo{
					{
						ParentZone:       "example.com",
						LoadBalancedZone: "cloud.example.com",
					},
				},
				ParentZoneDNSServers: []utils.DNSServer{{
					Host: server,
					Port: port,
				}},
			},
			expectedError: false,
			host:          "app.cloud.example.com",
			result: map[string]string{
				"eu": "gslb-ns-eu-cloud.example.com",
				"us": "gslb-ns-us-cloud.example.com",
			},
		},
		{
			name: "hit cloud.example.com on multiple DNS servers",
			config: &resolver.Config{
				ClusterGeoTag: "us",
				DelegationZones: []*resolver.DelegationZoneInfo{
					{
						ParentZone:       "example.com",
						LoadBalancedZone: "cloud.example.com",
					},
				},
				ParentZoneDNSServers: []utils.DNSServer{
					{
						Host: server,
						Port: port,
					},
					{
						Host: server,
						Port: port,
					},
				},
			},
			expectedError: false,
			host:          "app.cloud.example.com",
			result: map[string]string{
				"eu": "gslb-ns-eu-cloud.example.com",
			},
		},
		{
			name: "unsupported host",
			config: &resolver.Config{
				ClusterGeoTag: "us",
				DelegationZones: []*resolver.DelegationZoneInfo{
					{
						ParentZone:       "example.com",
						LoadBalancedZone: "cloud.example.com",
					},
				},
				ParentZoneDNSServers: []utils.DNSServer{{
					Host: server,
					Port: port,
				}},
			},
			expectedError: false,
			host:          "app.cloud.test.com",
			result:        map[string]string{},
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			ns, err := NewDynamic(test.config).GetExternalClusterNSNamesByHostname(test.host)
			if test.expectedError {
				assert.Error(t, err)
				return
			}
			assert.NoError(t, err)
			assert.True(t, utils.EqualAnnotations(test.result, ns))
		})
	}
}

// Checks whether local env is running.
func isDNSRunning(host string, port int) bool {
	address := fmt.Sprintf("%s:%d", host, port)
	timeout := 2 * time.Second

	dialer := &net.Dialer{Timeout: timeout}
	conn, err := dialer.DialContext(context.Background(), "tcp", address)
	if err != nil {
		return false
	}
	_ = conn.Close()
	return true
}
